package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.domain.dto.ContractDto;
import com.crm.domain.dto.ReportDto;
import com.crm.domain.entity.Activity;
import com.crm.domain.entity.Chll;
import com.crm.domain.entity.Report;
import com.crm.domain.entity.ReportContract;
import com.crm.domain.vo.*;
import com.crm.mapper.*;
import com.crm.service.ReportService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Resource
    private ReportMapper reportMapper;

    @Resource
    private ClueMapper clueMapper;

    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private ContractMapper contractMapper;
    @Autowired
    private ChllMapper chllMapper;

    /**
     * 统计线索数据
     *
     * @param dto
     * @return
     */
    @Override
    public RowsVO<Report> select(ReportDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Report> list = reportMapper.select(dto);
        RowsVO<Report> vo = new RowsVO<>();
        vo.setCode(200);
        vo.setRows(list);
        vo.setMsg("查询成功");
        vo.setTotal((long) list.size());
        return vo;
    }


    /**
     * 线索转化率漏斗图
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public OneVO getVulnerabilityMap(String beginCreateTime, String endCreateTime) {


        VulnerabilityMapVo mapVo = new VulnerabilityMapVo();
        //线索总数
        int cluesNums = clueMapper.getCluesNums(beginCreateTime, endCreateTime);
        //有效线索数
        int effectiveCluesNums = clueMapper.getEffectiveCluesNums(beginCreateTime, endCreateTime);
        //商机数量
        int businessNums = businessMapper.getBusinessNums(beginCreateTime, endCreateTime);
        //合同数量
        int contractNums = contractMapper.getContractNums(beginCreateTime, endCreateTime);
        mapVo.setCluesNums(cluesNums);
        mapVo.setEffectiveCluesNums(effectiveCluesNums);
        mapVo.setBusinessNums(businessNums);
        mapVo.setContractNums(contractNums);

        OneVO<VulnerabilityMapVo> vo = new OneVO<>();
        vo.setData(mapVo);
        vo.setCode(200);
        vo.setMsg("操作成功");
        return vo;
    }

    /**
     * 学科饼图统计
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public DataVO subjectStatistics(String beginCreateTime, String endCreateTime) {

        //查学科集合
        List<PieVO> projects = contractMapper.selectProject();


        DataVO<PieVO> vo = new DataVO<>();
        vo.setMsg("操作成功");
        vo.setCode(200);
        vo.setData(projects);
        return vo;
    }

    /**
     * 线索统计折线图
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVO cluesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            // 获取范围时间集合
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);

            List<LineSeriesVO> series = new ArrayList<>();
            List<Map<String, Object>> statistics = clueMapper.cluesStatistics(beginCreateTime, endCreateTime);

            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("新增线索数量");

            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();
            lineSeriesDTO2.setName("线索总数量");

            int sum = 0;
            for (String s : timeList) {
                Optional<Map<String, Object>> optional = statistics.stream()
                        .filter(d -> s != null && d.get("dd") != null && d.get("dd").equals(s))
                        .findFirst();

                if (optional.isPresent()) {
                    Map<String, Object> currentData = optional.get();
                    int num = Integer.parseInt(currentData.get("num").toString());
                    lineSeriesDTO1.getData().add(num);
                    sum += num;
                } else {
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }

            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // 可以在此添加日志记录或其他异常处理
            e.printStackTrace(); // 根据实际需求处理异常
        }

        return lineChartVo;
    }

    /**
     * 统计客户数据
     *
     * @param dto
     * @return
     */
    @Override
    public RowsVO<ReportContract> selectContract(ContractDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ReportContract> list = contractMapper.select(dto);
        RowsVO<ReportContract> vo = new RowsVO<>();
        vo.setCode(200);
        vo.setRows(list);
        vo.setMsg("查询成功");
        vo.setTotal((long) list.size());
        return vo;
    }

    /**
     * 客户统计折线图
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVO contractStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            // 获取范围时间集合
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("新增客户数");
            ArrayList<Integer> list01 = new ArrayList<>();
            list01.add(18);
            list01.add(25);
            list01.add(14);
            list01.add(10);
            list01.add(40);
            list01.add(17);
            list01.add(13);
            list01.add(4);
            lineSeriesDTO1.setData(list01);

            ArrayList<Integer> list02 = new ArrayList<>();
            list02.add(16);
            list02.add(30);
            list02.add(11);
            list02.add(10);
            list02.add(28);
            list02.add(55);
            list02.add(11);
            list02.add(33);
            LineSeriesVO lineSeriesDTO2 = new LineSeriesVO();

            lineSeriesDTO2.setName("客户总数");
            lineSeriesDTO2.setData(list02);


            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // 可以在此添加日志记录或其他异常处理
            e.printStackTrace(); // 根据实际需求处理异常
        }

        return lineChartVo;
    }


    /**
     * 销售统计折线图
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVO salesStatistics(String beginCreateTime, String endCreateTime) {
        LineChartVO lineChartVo = new LineChartVO();
        try {
            // 获取范围时间集合
            List<String> timeList = findDates(beginCreateTime, endCreateTime);
            lineChartVo.setxAxis(timeList);
            List<LineSeriesVO> series = new ArrayList<>();
            LineSeriesVO lineSeriesDTO1 = new LineSeriesVO();
            lineSeriesDTO1.setName("销售统计");
            ArrayList<Integer> list01 = new ArrayList<>();
            list01.add(28);
            list01.add(25);
            list01.add(21);
            list01.add(14);
            list01.add(21);
            list01.add(33);
            list01.add(34);
            list01.add(21);
            lineSeriesDTO1.setData(list01);

            series.add(lineSeriesDTO1);
            lineChartVo.setSeries(series);
        } catch (ParseException e) {
            // 可以在此添加日志记录或其他异常处理
            e.printStackTrace(); // 根据实际需求处理异常
        }

        return lineChartVo;
    }

    @Override
    public RowsVO<Chll> selectActive(Chll dto) {

        IPage<Chll> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<Chll> wrapper = new QueryWrapper<>();
        // 检查每个查询条件是否非空，然后添加到wrapper中
        if (dto.getName() != null && !dto.getName().isEmpty()) {
            wrapper.like("name", "%" + dto.getName() + "%");
        }

        if (dto.getCode() != null && !dto.getCode().isEmpty()) {
            wrapper.eq("code", dto.getCode());
        }

        if (dto.getChannel() != null && !dto.getChannel().isEmpty()) {
            wrapper.eq("channel", dto.getChannel());
        }

        IPage<Chll> chllIPage = chllMapper.selectPage(page, wrapper);

        RowsVO vo = new RowsVO();
        vo.setTotal(chllIPage.getTotal());
        vo.setCode(200);
        vo.setMsg("操作成功");
        vo.setRows(chllIPage.getRecords());
        return vo;
    }




    /**
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }



}
